package com.self.admin.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.self.admin.model.SysPrivilege;
import com.self.admin.service.SysPrivilegeService;
import com.self.common.exception.BusinessException;
import com.self.common.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @version v1.0
 * @ClassName: SysPrivilegeController
 * @Description:
 * @Author: Mac
 * @Date: 2022/6/4 16:55
 */
@RestController
@RequestMapping("/privileges")
@Api(tags = "权限的管理")
public class SysPrivilegeController {

    @Autowired
    private SysPrivilegeService sysPrivilegeService;

    @GetMapping
    @ApiOperation(value = "分页查询权限数据")
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    public R<Page<SysPrivilege>> getPage(Page<SysPrivilege> page){
        page.addOrder(OrderItem.desc("last_update_time"));
        return R.ok(sysPrivilegeService.page(page));
    }


    @PostMapping
    @ApiOperation(value = "新增一个权限")
    @PreAuthorize("hasAuthority('sys_privilege_create')")
    public R add(@Validated @RequestBody SysPrivilege sysPrivilege){
        sysPrivilegeService.save(sysPrivilege);
        return R.ok();
    }

    @PatchMapping
    @ApiOperation(value = "修改一个权限")
    @PreAuthorize("hasAuthority('sys_privilege_update')")
    public R update(@Validated @RequestBody SysPrivilege sysPrivilege){
        if (sysPrivilege.getId() == null) {
            throw new BusinessException("权限id不能为空");
        }
        sysPrivilegeService.updateById(sysPrivilege);
        return R.ok();
    }
}
